<?php
/**
 * Created by PhpStorm.
 * DateTime: 2020/11/3 17:47
 * Intro:
 */
namespace addons\podunk\controller\api;

use addons\podunk\controller\Base;
use addons\podunk\library\CLog;
use addons\podunk\library\traits\GoldCache;
use addons\podunk\model\Device;
use addons\podunk\model\Order;
use addons\podunk\model\Task;
use think\Exception;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Hook;
use think\Log;
use think\Request;

class Cloud extends Base
{
    use GoldCache;

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function getTask()
    {
        $params = $this->request->param();
        $time = time();
        $this->podunkValidate($params, get_class(), 'getTask');
        $key = $params['identity'].'_'.$params['uid'].'_'.$params['device_id'];
        $data = $this->getDeviceTaskList($key);
        if($data){
            if($data[0]->start_time < $time){
                //$this->removeTask($key, json_encode($data[0]));
                $this->success('获取任务成功', $data[0]);
            }else{
                $this->error('没有任务');
            }
        }else{
            $this->error('没有任务');
        }
    }

    public function addTaskRecord()
    {

        $params = $this->request->param();
        $key = $params['identity'].'_'.$params['uid'].'_'.$params['device_id'];

        $content = htmlspecialchars_decode($params['content']);
//        $content = str_replace('\\"', ' ',json_encode($content));
//        $content = trim($content, "\"");
        $contentJson = json_decode($content);
//        CLog::write($content->uuid);

        $this->removeTask($key, $contentJson->uuid);

        Task::where(['device_id'=>$params['device_id'],'status'=>'working'])->update(['status'=>'exception']);

        try{
            $task = Task::create([
                'task_name'=>$params['task_name'],
                'uuid'=>$params['uuid'],
                'user_id'=>$params['uid'],
                'device_id'=>$params['device_id'],
                'identity' => $params['identity'],
                'app' => $params['app'],
                'task' => $params['task'],
                'content' => $content,
                'status' => 'working',
            ]);
        }catch (Exception $e){
            Log::error(Request::instance()->controller().'---'.$e->getMessage());
        }


        $this->success('任务添加成功', $task);
    }

    public function updateTaskRecord()
    {
        $taskId =  $this->request->param('task_id');
        $status = $this->request->param('status');
        $log = $this->request->param('log');
        $task = Task::get($taskId);
        $task->status = $status;
        $task->log = $log;
        $task->save();
        $this->success('任务更新成功');
    }

    public function verify()
    {
        $params = $this->request->param();
        $this->podunkValidate($params, get_class(), 'auth');
        $identity = $params['identity'];
        $app = $params['app'];

        $device = Device::get(['identity'=>$identity]);
        if($device){
            $device->app = $app;
            $device->save();
            $this->success('认证成功',$device);
        }else{
            $this->error('设备未授权');
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function createOrder()
    {
        $params = $this->request->param();

        $data['task_name'] = $params['task_name'];
        $data['product_name'] = $params['product_name'];
        $data['user_id'] = $params['uid'];
        $data['device_id'] = $params['device_id'];
        $data['task_id'] = $params['task_id'];
        $data['identity'] = $params['identity'];
        $data['app'] = $params['app'];
        $data['task'] = $params['task'];
        $data['order_number'] = $params['order_number'];
        $data['consignee'] = $params['consignee'];
        $data['address'] = $params['address'];
        $data['mobile'] = $params['mobile'];
        $data['screenshot'] = $params['screenshot'];
        $data['status'] = $params['status'];

        Order::create($data);
        $this->success('订单创建成功');
    }

    public function updateOrder()
    {
        $params = $this->request->param();
        $orderId = $params['order_id'];
        $status = $params['status'];
        Order::update(['id'=>$orderId, 'status'=>$status]);
		Log::debug($orderId.'更新状态----'.$status);
        $this->success('订单更新成功');
    }

    public function addtest()
    {
        $redis = $this->getRedis();
        $list = $redis->lRange('tiktokstore-e92cdefcde_1_14',0,-1);
        foreach ($list as $l){
            $a = json_decode($l);
            echo $a->uuid;
            if($a->uuid == 'c7309d4c-7835-e553-f866-e7b6a839530c'){
                $redis->lRem('tiktokstore-e92cdefcde_1_14', $l);
            }
            echo '</br>';

        }
        //$this->test('aaa_1_1');
//        $datas = [
//            ['id'=>'dwedewdewd','time'=>'10000001'],
//            ['id'=>'dwedewdewd','time'=>'10000201'],
//            ['id'=>'dwedewdewd','time'=>'10000004'],
//            ['id'=>'dwedewdewd','time'=>'10000051'],
//            ['id'=>'dwedewdewd','time'=>'10001001'],
//            ['id'=>'dwedewdewd','time'=>'10000021'],
//            ['id'=>'dwedewdewd','time'=>'10000008']
//        ];
//
//        foreach ($datas as $data){
//            $this->test('aaa_1_1',$data);
//        }
//
//        $file_path = "uploads/20201117/9e0aee3fd616d6794de0904b8bd706e8.txt";
//        $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
//        $str = str_replace("\n","<br />",$str);
//        echo $str;
    }
}